const App = {
  mixins: [Save],//配置文件，路径/utils/mixins.js
  data() {
    return {
      photo,
      ID_Card: [],
      dataForm: {
        Party_Member_SerialNumber: '',
        Personal_Resource: '1',
        Political_Affiliation: '中共党员'
      },
      dataForm1: {
        RR_County_Nubmer: '232723',
        Personal_Resource: '1',
        Political_Affiliation: '中共党员'
      },
      childDataForm: [{
        Type: 0,
        fileList: [],
        Children: {
          party_member_event_attachment: [],
        }
      }, {
        Type: 1,
        fileList: [],
        Children: {
          party_member_event_attachment: [],
        }
      }],
      type: '',
      childDataForm1: [],
      rules: {

      },
      Affiliation: [
        {
          value: "部长",
          label: "部长",
        },
        {
          value: "副部长",
          label: "副部长",
        },
        {
          value: "科长",
          label: "科长",
        },
        {
          value: "科员",
          label: "科员",
        },
      ],
      Manager: [],
      Nation: [],
      fileList: [],
      Ducation: ducation(),
      city: [],
      city1: [],
      cityValue: [],
      Category: [],
      Position: [],
      is: false,
      childDataForm2: [],
      childDataForm3: [],
      party_member_attachment_type: [],
      showDialog: false,
      fileUrl: '',
    };
  },
  mounted() {
    let ls_URL = window.location.href;
    this.type = getQueryObject(ls_URL, "type");// 获取 nodeKey 参数
    this.getCategory();
    this.changeCity(this.dataForm1.RR_County_Nubmer)
  },
  watch: {
    'dataForm.ID_Card_Number'(val) {
      this.dataForm1.ID_Card_Number = val;
    },
    'dataForm.Party_Member_SerialNumber'() {
      if (this.action == 'Modify') {
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
          method: "post",
          data: {
            Data: "personal_information", //表名
            Condition: "ID_Card_Number='" + this.dataForm.ID_Card_Number + "'",
          },
          success: (res) => {
            if (res.length == 1) {
              this.dataForm1 = res[0];
              this.cityValue = [this.dataForm1.RR_Province_Number, this.dataForm1.RR_City_Number, this.dataForm1.RR_County_Nubmer, this.dataForm1.RR_Town_Number];
              this.is = false;
            } else {
              this.is = true;
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
        });
      }
    },
    childDataForm(val) {
      console.log(val);
    }
  },
  computed: {
    File_Type() {
      return function (row) {
        try {
          return this.party_member_attachment_type.filter(i => i.File_Type_SerialNumber == row.File_Type)[0].File_Type;
        } catch (error) {
          return ''
        }

      }
    }
  },
  methods: {
    success1(row) {

    },
    remove1(row) {

    },
    preview(row) {
      if (row.Attachment_URL) {
        this.fileUrl = photo + row.Attachment_URL;
      } else {
        this.fileUrl = photo + row.File_Name;
      }
      this.showDialog = true;
    },
    async download(row) {
      let apiUrl = '';  let fileName = '';
      if (row.Attachment_URL) {
        apiUrl = photo + row.Attachment_URL;
        fileName = apiUrl.split('/').pop();
      } else {
        // window.location.href = photo + row.File_Name;
        apiUrl = photo + row.File_Name;
        fileName = apiUrl.split('/').pop();
      }
      try {
        const response = await fetch(apiUrl);
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = fileName || 'download';
        document.body.appendChild(a);
        a.click();

        // 清理
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
      } catch (error) {
        console.error('下载失败:', error);
      }
    },
    preview1(row) {
      if (row.Attachment_URL) {
        this.fileUrl = photo + row.Attachment_URL;
      } else {
        this.fileUrl = photo + row.File_Name;
      }
      this.showDialog = true;
    },
    shibie(val) {
      if (this.action == 'Add') {
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/generalQueryByTableName`,
          method: "post",
          data: {
            Data: "personal_information", //表名
            Condition: "ID_Card_Number='" + val + "'",
          },
          success: (res) => {
            if (res.length == 1) {
              this.dataForm1 = res[0];
              this.cityValue = [this.dataForm1.RR_Province_Number, this.dataForm1.RR_City_Number, this.dataForm1.RR_County_Nubmer, this.dataForm1.RR_Town_Number];
              this.is = false;
            } else {
              if (ID_Validity(val)) {
                this.dataForm1.Gender = Return_SexByID(val)
                this.dataForm1.Birthday = Return_BirthdayByID(val)
              }
              this.is = true;
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
        });
      }
    },
    getData(nodeKey) {//查询
      const { primary_key } = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: 'party_member_information',
          Condition: `${primary_key}='${nodeKey}'`,
        },
        success: (res) => {
          console.log(res);
          this.dataForm = res[0];
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: 'party_member_event',
          Condition: `${primary_key}='${nodeKey}'`,
        },
        success: (res) => {
          let str = res.map(i => "'" + i.Event_SerialNumber + "'").join(',')
          $.ajax({
            headers: requestHeaders(),
            url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
            method: "post",
            data: {
              Data: 'party_member_event_attachment',
              Condition: `Event_SerialNumber IN (${str ? str : "''"}) AND Row_Status='0'`,
            },
            success: (data) => {
              res.forEach(item => {
                let party_member_event_attachment = data.filter(i => i.Event_SerialNumber == item.Event_SerialNumber);
                let arr = [];
                party_member_event_attachment.forEach(item => {
                  item.name = item.Attachment_Name + "（磁盘文件名:" + item.Attachment_URL + "）"
                  arr.push(item)
                })
                item.fileList = arr;
                item.Children = {
                  party_member_event_attachment,
                }
              })
              this.childDataForm = res;
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest)
            },
          });
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: 'party_member_attachment',
          Condition: `${primary_key}='${nodeKey}' AND Row_Status='0'`,
        },
        success: (res) => {
          let arr = [];
          res.filter(i => i.Place_File != '1').forEach(item => {
            item.name = item.File_NameOri + "（磁盘文件名:" + item.File_Name + "）"
            arr.push(item)
          })
          this.fileList = arr;
          this.childDataForm1 = res;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: 'party_member_attachment_type',
          Condition: `Row_Status='0'`,
        },
        success: (res) => {
          this.party_member_attachment_type = res;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
      });
    },
    changeCity(val) {
      if (val) {
        this.dataForm1.RR_Province_Number = val.substring(0, 2) + '0000';
        this.dataForm1.RR_City_Number = val.substring(0, 4) + '00';
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/clientOperation/getDistrictTree`,
          type: "GET",
          data: {
            DistrictCode: val,
          },
          success: (data) => {
            this.city1 = data[0].children;
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
          dataType: "json",
        });
      } else {
        this.dataForm1.Registered_Residence = '';
        this.dataForm1.RR_Province_Number = '';
        this.dataForm1.RR_City_Number = '';
        this.dataForm1.RR_County_Nubmer = '';
        this.dataForm1.RR_Town_Number = '';
        this.dataForm1.RR_Village_Number = '';
      }
    },
    changeCity1(val) {
      let Province = this.city.filter(i => i.value == (val.substring(0, 2) + '0000'))[0];
      let City = Province.children.filter(i => i.value == (val.substring(0, 4) + '00'))[0];
      let County = City.children.filter(i => i.value == (val.substring(0, 6)))[0];
      let Town = this.city1.filter(i => i.ProvinceNumber == (val.substring(0, 9)))[0];
      let Village = Town.children.filter(i => i.ProvinceNumber == val)[0];
      this.dataForm1.Registered_Residence = Province.label + City.label + County.label + Town.Province + Village.Province;
      this.dataForm1.RR_Town_Number = val.substring(0, 9);
    },
    async handleSubmit() {
      const allValid = await this.validateAllForms();
      if (allValid) {
        this.loading = true;
        let ls_URL = window.location.href;
        const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        let lJSONObject_Data_Options = new Object();
        lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

        let ls_MainTableName = lJSONObject_Data_Options.TableName;
        let ls_DataForm = lJSONObject_Data_Options.form;
        let ls_primary_key = lJSONObject_Data_Options.primary_key;
        //没有子表下面内容就会报错，try/catch抛出异常
        try {
          //可能涉及多个子表
          document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
            let lJSONObject_ChildData_Options = new Object();
            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
            if (this[ls_DataForm][ls_primary_key]) {
              this[ls_ChildDataForm].forEach(item => {
                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
              })
            }
            //建立子表结构体
            let JSONArray_ChildRecord = new Array();
            JSONArray_ChildRecord = this[ls_ChildDataForm];
            if (!this[ls_DataForm].Children) {
              this[ls_DataForm].Children = new Object();
            }
            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
          })
        } catch (error) {

        }
        //建立新增提交结构
        let lJSONObject_DataSet = new Object();
        if (action == 'Add') {
          if (this.nodeKey) {
            this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
          }
          let lJSONObject_Table = new Object();
          if (!this[ls_DataForm]['Children']) {
            this[ls_DataForm].Children = new Object();
          }
          this[ls_DataForm]['Children']['party_member_category_log'] = [{
            Party_Member_Category_SerialNumber: this.dataForm.Party_Member_Category_SerialNumber,
          }]
          if (this.is) {
            this['dataForm1'].Migrant_Personal = (this['dataForm1'].RR_County_Nubmer == '232723' ? '0' : '1')
            this['dataForm1']['Children'] = {
              party_member_information: [deepClone(this[ls_DataForm])]
            }
            let lJSONArray_Record = new Array();
            lJSONArray_Record.push(this['dataForm1']);
            lJSONObject_Table['personal_information'] = lJSONArray_Record;
            //手机号不能有重复
            lJSONObject_Table['personal_Contact_Phone'] = [{ Contact_Phone: this['dataForm1'].Contact_Phone }];
          } else {
            let lJSONArray_Record = new Array();
            lJSONArray_Record.push(this[ls_DataForm]);
            lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
          }
          lJSONObject_DataSet[action] = lJSONObject_Table;
          lJSONObject_DataSet[action]['party_member_information_add_config'] = [{
            ID_Card_Number: this[ls_DataForm].ID_Card_Number,
          }]

        } else if (action == 'Modify') {
          const { add, modify } = this.deal(this[ls_DataForm]);
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(modify);

          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

          lJSONObject_Table['personal_information'] = [this.dataForm1];

          lJSONObject_DataSet[action] = lJSONObject_Table;
          if (add != null) {
            let lJSONArray_Record_Add = new Array();
            lJSONArray_Record_Add.push(add);

            let lJSONObject_Table_Add = new Object();
            lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

            lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
          }
          if (!lJSONObject_DataSet['Add']) {
            lJSONObject_DataSet['Add'] = new Object();
          }
          lJSONObject_DataSet['Add']['party_member_event_attachment'] = this.childDataForm2;
          if (this[ls_DataForm].Party_Member_Category_SerialNumber != this[ls_DataForm].Party_Member_Category_SerialNumber_Original) {
            let party_member_category_log = [{
              Party_Member_Category_SerialNumber: this.dataForm.Party_Member_Category_SerialNumber,
              Party_Member_SerialNumber: this.dataForm.Party_Member_SerialNumber,
            }]
            lJSONObject_DataSet['Add']['party_member_category_log'] = party_member_category_log;
          }
        }
        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        if (!lJSONObject_DataSet['Add']) {
          lJSONObject_DataSet['Add'] = new Object();
        }
        lJSONObject_DataSet['Add']['base_operation_log'] = [{
          Operation_Type: '0',
          Operation_Path: this.relativePath,
          Operation_Main,
          Operation_Interface: "generalSave",
          Operation_IP: getIpAddress()
        }]
        submitSave(lJSONObject_DataSet, (res) => {
          if (res.Status == 'success') {
            window.location.href = './index.html'
          } else {
            this.$message({
              message: '添加失败，可能原因1.当前党员已存在，2.新人员数据时手机号已存在',
              type: 'error'
            })
          }
          this.loading = false;
        })
      }
    },
    getCategory() {
      $.ajax({
        url: absolutepath() + "api/Nation.json",
        type: "GET",
        success: (data) => {
          this.Nation = data;
        },
        dataType: "json",
      });
      $.ajax({
        url: `${absolutepath()}api/Districtjl.json`,
        method: "get",
        success: (data) => {
          data.forEach((item) => {
            item.children.forEach((ite) => {
              ite.children.forEach((it) => {
                it.children = undefined;
              });
            });
          });
          this.city = data;
        }
      });
      $.ajax({
        headers: requestHeaders(),
        type: "POST",
        url: mh + "/generalBusiness/generalQueryByTableName",
        data: {
          Data: "party_member_position", //指定要查询的数据库表名
          Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
        },
        success: (Result) => {
          this.Position = Result;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        type: "POST",
        url: mh + "/generalBusiness/generalQueryByTableName",
        data: {
          Data: "party_member_category", //指定要查询的数据库表名
          Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
        },
        success: (Result) => {
          this.Category = Result;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        type: "POST",
        url: mh + "/generalBusiness/generalQueryByTableNameWithOriginal",
        data: {
          Data: "personal_information", //指定要查询的数据库表名
          Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
        },
        success: (Result) => {
          this.ID_Card = Result;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
        type: "GET",
        data: {
          TableName: 'party_organization',
          NodeCode: '',
        },
        success: (data) => {
          this.Manager = data; // 直接使用 this
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      // $.ajax({
      //   headers: requestHeaders(),
      //   type: "POST",
      //   url: mh + "/generalBusiness/generalQueryByTableName",
      //   data: {
      //     Data: "party_member_attachment", //指定要查询的数据库表名
      //     Condition: "Party_Member_SerialNumber='" + this.nodeKey + "' AND File_Type='2'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
      //   },
      //   success: (Result) => {
      //     this.childDataForm3 = Result.map(i => {
      //       return {
      //         ...i, Attachment_Name: i.File_NameOri, Attachment_URL: i.File_Name,
      //       }
      //     });
      //   },
      //   complete: (XMLHttpRequest) => {
      //     requestPretreatment(XMLHttpRequest);
      //   },
      //   dataType: "json",
      // });
    },
    handleAdd(Type) {
      this.childDataForm.push({
        Type,
        fileList: [],
        Children: {
          party_member_event_attachment: [],
        }
      })
    },
    handleRemove(Type) {
      if (this.childDataForm.filter(i => i.Row_Status != '1' && i.Type == Type).length > 1) {
        let i = this.childDataForm.filter(i => i.Row_Status != '1' && i.Type == Type).length - 1
        let obj = this.childDataForm.filter(i => i.Row_Status != '1' && i.Type == Type)[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.childDataForm = this.childDataForm.filter((x, id) => x.Type == Type && id != i);
        } else {
          this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.childDataForm.filter(item => item.Row_Status != '1' && item.Type == Type)[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    success(row, res, arr, id, value) {
      console.log(value);
      //添加正常主子表提交
      if (!value) {
        let obj = {
          uid: row.uid,
          Attachment_URL: res.fileName,
          Attachment_Name: row.name,
          Temp_Path: res.tempPath,
        }
        obj[id] = value;
        arr.push(obj)
      } else {//添加直接上传新表，因为有主键
        let obj = {
          uid: row.uid,
          Attachment_URL: res.fileName,
          Attachment_Name: row.name,
          Temp_Path: res.tempPath,
        }
        obj[id] = value;
        if (id == 'Party_Member_SerialNumber') {
          arr.push(obj);
        } else {
          this.childDataForm2.push(obj);
        }
      }
    },
    remove(row, res, arr, id, value) {
      if (this.action == 'Add') {
        arr = arr.filter(i => i.uid != row.uid);
      } else {
        if (!Object.keys(row).some(item => item.includes('_Original'))) {
          if (id == 'Party_Member_SerialNumber') {
            arr = arr.filter(i => i.uid != row.uid);
          } else {
            this.childDataForm2 = this.childDataForm2.filter(i => i.uid != row.uid);
          }
        } else {
          let obj = arr.filter(i => i[id] == row[id])[0];
          obj.Row_Status = '1'
        }
      }
    },
    success1(row, res, arr, id, value, File_Type) {
      if (!value) {
        let obj = {
          uid: row.uid,
          File_Name: res.fileName,
          File_NameOri: row.name,
          File_Path: res.tempPath,
          File_Type,
        }
        obj[id] = value;
        arr.push(obj)
      } else {//添加直接上传新表，因为有主键
        let obj = {
          uid: row.uid,
          File_Name: res.fileName,
          File_NameOri: row.name,
          File_Path: res.tempPath,
          File_Type,
        }
        obj[id] = value;
        if (id == 'Party_Member_SerialNumber') {
          arr.push(obj);
        } else {
          this.childDataForm2.push(obj);
        }
      }
    },
    remove(row, res, arr, id) {
      if (this.action == 'Add') {
        arr = arr.filter(i => i.uid != row.uid);
      } else {
        if (!Object.keys(row).some(item => item.includes('_Original'))) {
          if (id == 'Party_Member_SerialNumber') {
            arr = arr.filter(i => i.uid != row.uid);
          } else {
            this.childDataForm2 = this.childDataForm2.filter(i => i.uid != row.uid);
          }
        } else {
          let obj = arr.filter(i => i[id] == row[id])[0];
          obj.Row_Status = '1'
        }
      }
    },
  },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader);
app.component('yl-online-preview', ylOnlinePreview);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
